import 'package:flutter/material.dart';
import 'package:get/get.dart';

class SearchController extends GetxController {
  final searchResults = <String>[].obs;
  final searchText = ''.obs; // 新增响应式变量
  final hotSearches = <String>[
    '热门搜索1',
    '热门搜索2',
    '热门搜索3',
    '热门搜索4',
    '热门搜索5',
    '热门搜索6',
    '热门搜索7',
    '热门搜索8',
    '热门搜索9',
    '热门搜索10',
    '热门搜索11',
    '热门搜索12',
  ].obs;
  final searchHistory = <String>[].obs;
  final searchTextController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    loadSearchHistory();
    // 监听文本变化
    searchTextController.addListener(() {
      searchText.value = searchTextController.text;
    });
  }

  @override
  void onClose() {
    searchTextController.dispose();
    super.onClose();
  }

  void search() {
    final query = searchText.value.trim();
    if (query.isNotEmpty) {
      // TODO: 实现实际的搜索逻辑
      searchResults.value = ['Result 1', 'Result 2', 'Result 3'];
      addSearchHistory(query);
    } else {
      searchResults.clear();
    }
  }

  void loadSearchHistory() {
    // TODO: 从本地存储中加载搜索历史
    searchHistory.value = [
      '历史1',
      '历史搜索2',
      '历史搜索3',
      '历史搜索4',
      '历史5',
      '历史搜索6',
      '历史搜索7',
      '历史搜索8',
    ];
  }

  void addSearchHistory(String query) {
    searchHistory.remove(query);
    searchHistory.insert(0, query);
    if (searchHistory.length > 10) {
      searchHistory.removeLast();
    }
    // TODO: 将搜索历史保存到本地存储
  }

  void clearSearchHistory() {
    searchHistory.clear();
    // TODO: 将清空后的搜索历史保存到本地存储
  }

  void clearSearch() {
    searchText.value = '';
    searchResults.clear();
    searchTextController.clear();
  }
}
